package com.example.length;


import com.example.length.printer.LengthPrinter;
import com.example.length.printer.SimpleLengthPrinter;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

public abstract class LengthPrintBridge<PRINTER extends LengthPrinter> {

    private Length length;
    private LengthPrinter lengthPrinter;

    public LengthPrintBridge(Length length) {
        this.length = length;

        try {
            this.lengthPrinter = getLengthPrinterClass().getConstructor().newInstance();
        } catch (NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) {
            this.lengthPrinter = new SimpleLengthPrinter();
        }

    }

    void print(){
        lengthPrinter.print(length);
    }


    public Length getLength() {
        return length;
    }

    public void setLength(Length length) {
        this.length = length;
    }

    public LengthPrinter getLengthPrinter() {
        return lengthPrinter;
    }

    private Class<? extends LengthPrinter> getLengthPrinterClass(){
        Type type = this.getClass().getGenericSuperclass();
        ParameterizedType p = (ParameterizedType) type;
        //noinspection unchecked
        return (Class<? extends LengthPrinter>) p.getActualTypeArguments()[0];
    }

}
